"use client";
import { FC, useEffect, useRef, useState } from "react";
import { useRouter } from "@/i18n/routing"; // Assuming router logic
import { useTranslations } from "next-intl"; // Assuming translations

interface Props {
  brand_id: string;
  token: string;
}

const SportsClient: FC<Props> = (props) => {
  const { brand_id, token } = props;
  const [currentToken, setCurrentToken] = useState(token);

  const btRef = useRef(null);
  const router = useRouter();
  const isFreshRef = useRef(false);

  // Effect to dynamically load the script on client mount
  useEffect(() => {
    if (typeof window !== "undefined") { // Make sure it's only executed on the client
      const script = document.createElement("script");
      script.src = "https://ui.invisiblesport.com/bt-renderer.min.js";
      script.async = true;
      script.onload = () => {
        console.log("onLoad=====> Script Loaded and Initialized");
        onLoad();
      };
      document.body.appendChild(script);

      // Cleanup when the component is unmounted
      return () => {
        console.log("onLoad=====> Clean up");
        if (btRef.current) {
          // @ts-ignore
          btRef.current?.kill();
          btRef.current = null;
        }
        document.body.removeChild(script); // Remove script when component unmounts
      };
    }
  }, [currentToken]); // Trigger the effect when `currentToken` changes

  // Update token and re-initialize if necessary
  const updateToken = (newToken: string) => {
    if (currentToken !== newToken) {
      setCurrentToken(newToken);
      // @ts-ignore
      if (window.BTRenderer) {
        onLoad();
      }
    }
  };

  // Handle initialization when script is loaded
  const onLoad = () => {
    // @ts-ignore
    const bt = new BTRenderer();
    btRef.current = bt;
    console.log("onLoad=====> Initialized with token:", token);
    bt.initialize({
      brand_id: brand_id,
      token: currentToken,
      onTokenExpired: () => console.log("Token expired, handle refresh"),
      onSessionRefresh: () => {
        console.log("onSessionRefresh triggered");
        if (btRef.current) {
          // @ts-ignore
          btRef.current?.kill();
        }
        isFreshRef.current = true;
        router.refresh();
      },
      themeName: "default",
      lang: "pt-br",
      target: document.getElementById("betby"),
      betSlipOffsetBottom: 80,
      betSlipZIndex: 1000,
      stickyTop: 0,
      betSlipOffsetTop: 50,
      onRecharge: function () {
        router.push("/deposit");
      },
    });
  };

  return <div id="betby" className="h-[100%]"></div>;
};

export default SportsClient;
